//
//  DataBaseManager.m
//  QuickCure
//
//  Created by 马文星 on 16/5/2.
//  Copyright © 2016年 Demos. All rights reserved.
//

#import "DataBaseManager.h"

@implementation DataBaseManager

//单例
static DataBaseManager *manager = nil;
+ (instancetype)sharedmanager{
    
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        //1.
        manager = [[DataBaseManager alloc] init];
        
    });
    return manager;
}

//具体路径
- (instancetype)init{
   self =  [super init];
    
    if (self) {
    
        _isDatabaseOpened = NO;
        
        //数据库路径
        self.writablePath = [DatabaseDirectory() stringByAppendingPathComponent:@"data.sqlite"];
        
        loggerWarn(@"路径 = %@",DatabaseDirectory());
        
        [self openDataBase];
    }
    
    return self;
}

/*!
 *  打开数据库
 */
- (void)openDataBase{

    _databaseQueue = [FMDatabaseQueue databaseQueueWithPath:self.writablePath];
    
    if (!_databaseQueue) {
        
        _isDatabaseOpened = NO;
        return;
    }
    
    loggerWarn(@"打开数据库成功");

    _isDatabaseOpened = YES;
    
    //为数据库设置缓存，提高查询效率
    [_databaseQueue inDatabase:^(FMDatabase *db) {
        
        db.shouldCacheStatements = YES;
    }];
}

/*!
 *  关闭数据库
 */
- (void)closeDataBase{

    if (_isDatabaseOpened == NO) { //本来就关闭的
        
        loggerError(@"数据库关闭失败");
        return;
    }

    [_databaseQueue close];
    
    _isDatabaseOpened = NO;

    loggerWarn(@"关闭数据库成功");
}

/*!
 *  销毁数据库
 */
- (void)releaseManager{

    if (manager) {
        
        manager = nil;
    }
}

-(void)dealloc{

    [self closeDataBase];
}

@end
